<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\common\validate\PersonnelAddValidate;
use app\common\validate\PersonnelEditValidate;

use app\admin\model\Department;

use think\Exception;
use think\Request;

/**
 * 工作人员
 */
class User extends Base
{

    public function _initialize() {
        parent::_initialize();

        $departmentId = $this->request->param('departmentId');
        $defaultWhere['departmentId'] = $departmentId;
        $defaultWhere['status'] = 1;
        $defaultWhere['type'] = ['in', [0,1]];
        $this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'p_name' => [
                'label'     => '姓名',
                'field'     => 'p_name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
            /*'departmentId' => [
                'label'     => '部门',
                'field'     => 'departmentId',
                'type'      => 'select',
                'disabled'  => false,
                'condition' => '=',
                'data' => BaseHelper::makeOptions(
                    model('department'),
                    ['status'=> 1],
                    ['sorting'=> 'ASC'],
                    ['0' => '所有']
                )
            ],*/
        ];
        $this->redirect = url('admin/user/index', ['departmentId' => $departmentId]);
        $this->defaultOrder = 'createDate ASC';

        $this->assign('departmentId', $departmentId);
        $departmentName = Department::where('id', $departmentId)->value('name');
        $this->assign('departmentName', $departmentName);
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);
            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }
            //$where['type'] = ['in', [0,1]];
            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as &$item) {
                $department = \app\admin\model\Department::where(['id' => $item->departmentId])->value('name');

                $item->department = $department;
                if(empty($item['p_imgUrl'])){
                    if($item->sex == 1){
                        $item->p_imgUrl = config('sys.defaultsex1.png');
                    }else{
                        $item->p_imgUrl = config('sys.defaultsex2.png');
                    }
                }
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }
        return parent::index();
    }

    public function add(){
        //部门
        $Department = \app\admin\model\Department::where('status',1)->select();
        return $this->fetch('',[
            'departmentList' => $Department
        ]);
    }
    public function addPost(Request $request){
        if($request->isPost()){
            try{
                (new PersonnelAddValidate())->goCheck();
            }catch(Exception $e){
                return $this->error('参数异常');
            }
            $param = $request->param();
            if(empty($param['password'])){
                $param['password'] = '123456';
            }
            $param['password'] = BaseHelper::passwordEncrypt($param['password']);

            $model = \app\admin\model\User::where('username',$param['username'])->find();
            if($model){
                if($model->status == 1){
                    return $this->error('该员工已经存在');
                }else{
                    //如果该员工被禁用了，则直接修改状态
                    $model->status = 1;
                    if($param['is_partymember'] == 0){
                        $model->is_partymember = 0;
                        unset($param['partyTime']);
                    }else{
                        $model->is_partymember = 1;
                        $model->partyTime = $param['partyTime'];
                    }
                    if(empty($param['p_imgUrl'])){
                        unset($param['p_imgUrl']);
                    }

                }
            }else{
                $id = BaseHelper::getUUID();
                $param['id'] = $id;
                if($param['is_partymember']==0){
                    unset($param['partyTime']);
                }
                if(empty($param['p_imgUrl'])){
                    if($param['sex'] == 1){
                        $param['p_imgUrl'] = config('sys.defaultsex1');
                    }else{
                        $param['p_imgUrl'] = config('sys.defaultsex2');
                    }
                }
                $model = new \app\admin\model\User();
            }
            $result = $model->save($param);

            if($result != false){
                return $this->success('添加成功！', $this->redirect);
            }else{
                return $this->error('添加失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }
    public function edit(Request $request){
        $param = $request->param();
        $Personnel = \app\admin\model\User::get($param['id']);
        $Department = \app\admin\model\Department::where(true)->select();

        return $this->fetch('',[
            'data' => $Personnel,
            'departmentList' => $Department
        ]);
    }
    public function editPost(Request $request){
        if($request->isPost()){
            try{
                (new PersonnelEditValidate())->goCheck();
            }catch(Exception $e){
                return $this->error('参数异常');
            }
            $param = $request->param();
            $id = $param['id'];
            unset($param['id']);
            if($param['is_partymember']==0){
                unset($param['partyTime']);
            }
            if(empty($param['p_imgUrl'])){
                if($param['sex'] == 1){
                    $param['p_imgUrl'] = config('sys.defaultsex1');
                }else{
                    $param['p_imgUrl'] = config('sys.defaultsex2');
                }
            }
            $model = new \app\admin\model\User();
            $result = $model->save($param,['id'=>$id]);
            if($result != false){
                return $this->success('修改成功！', $this->redirect,2);
            }else{
                return $this->error('修改失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function detail(Request $request){
        $param = $request->param();
        $Personnel = \app\admin\model\User::get($param['id']);
        $Department = \app\admin\model\Department::where(true)->select();

        return $this->fetch('',[
            'data' => $Personnel,
            'departmentList' => $Department
        ]);
    }

    /**
     * 删除
     */
    public function delete(Request $request)
    {
        $id = $request->param('id');
        $model = model($this->model);
        $where = [
            'id' => $id
        ];
        $result = $model->where($where)->update(['status' => 2]);
        if($result !== false) {
            return $this->success('删除成功', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('删除失败 !');
        }
    }

    /**
     * 检查登录帐号是否已存在
     */
    public function checkUsername(){
        if($this->request->isAjax()){
            $username = $this->request->param('username');
            $model = model($this->model);

            $result = $model->where(['username' => $username, 'status' => 1])->field('username')->find();

            if($result){
                return json(['status' => 1]);
            }else{
                return json(['status' => 0]);
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['p_name']) && $filter['p_name']){
                $where['p_name'] = ['like', '%'.$filter['p_name'].'%'];
            }
            if(isset($filter['departmentId']) && $filter['departmentId']){
                $where['departmentId'] = $filter['departmentId'];
            }
        }

        return $where;
    }

    /**
     * 下载Excel模板
     */
    public function downloadTemplate(){
        \app\admin\service\Personnel::downloadTemplate($this->request);
    }

    /**
     * 导入数据
     */
    public function import(){
        $result = \app\admin\service\Personnel::import();

        return $result;
    }

    /**
     * 导出数据
     */
    public function export(){
        $result = \app\admin\service\Personnel::export($this->request);
        if($result['code'] == 2){
            $this->error($result['msg'], $this->redirect);
        }

        return redirect('admin/user/index', ['departmentId' => $this->request->param('departmentId')]);
    }

}